﻿using System;
using System.Diagnostics;
using SmartHRMS.Model.Account;
using StructureMap;

namespace SmartHRMS.UI.Web
{
    public class BasePage : System.Web.UI.Page
	{

        private IPrincipalService _ICustomPrincipalService= ObjectFactory.GetInstance<IPrincipalService>();

        public BasePage()
		{
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
            this.Load += new System.EventHandler(this.BasePage_Load);
            this.Error += new System.EventHandler(this.BasePage_Error);
		}

		protected void LogEvent(string message, EventLogEntryType entryType)
		{
			if (!EventLog.SourceExists("SmartHRMS"))
			{
                EventLog.CreateEventSource("SmartHRMS", "Application");
			}
            EventLog.WriteEntry("SmartHRMS", message, entryType);
		}

        protected void BasePage_Error(object sender, System.EventArgs e)
		{
			string errMsg;
			Exception currentError = Server.GetLastError();

			errMsg = "<link rel=\"\" href=\"\">";
			errMsg += "<h2>Smart Human Resource Management System [no version yet]-Page Error</h2><hr/>An unexpected error has occurred on this page. The system " +
				"administrators have been notified. Please feel free to contact us with the information " +
				"surrounding this error.<br/>"+
				"The error occurred in: "+Request.Url.ToString()+"<br/>"+
				"Error Message: <font class=\"\">"+ currentError.Message.ToString() + "</font><hr/>"+
				"<b>Stack Trace:</b><br/>"+
				currentError.ToString();

			if ( !(currentError is SmartHRMS.CustomExceptions.Infrastructure.ApplicationException) )
			{
				LogEvent( currentError.ToString(), EventLogEntryType.Error );
			}

			Response.Write( errMsg );
			Server.ClearError();
		}


        private void BasePage_Load(object sender, System.EventArgs e)
		{										
            if (!_ICustomPrincipalService.Identity.IsAuthenticated){
                Response.Redirect("~/DefaultPage.aspx");
              
            }
		}
    }
}
